package com.monolith.jd.demo.common.util;

import com.monolith.jd.demo.common.vo.JdAuthorizationSource;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 2018/10/1 Create by 郭文梁
 * JdAuthorizationUtil
 * 京东签名工具
 *
 * @author 郭文梁
 * @date 2018/10/1
 */
public class JdAuthorizationUtil {

    private JdAuthorizationUtil() {
    }

    private static HMacSignatureBuilder getHMacSignatureBuilder(JdAuthorizationSource source) {
        return new HMacSignatureBuilder()
                .signature(Md5Helper.encode(source.getKey() + source.getRegisterNo()))
                .scheme(source.getSchema())
                .host(source.getHost())
                .method(source.getMethod())
                .resource(source.getResource())
                .contentType(source.getContentType())
                .siteCode(source.getSiteCode())
                .registerNo(source.getRegisterNo())
                .opCode(source.getOpCode())
                .date(source.getDate())
                .content(source.getContent());
    }

    public static String getAuthorization(JdAuthorizationSource source) {
        HMacSignatureBuilder builder = getHMacSignatureBuilder(source);
        return builder.buildAsBase64String();
    }

    public static Map<String, String> generateHeaders(JdAuthorizationSource authorizationSource) {
        HMacSignatureBuilder builder = getHMacSignatureBuilder(authorizationSource);
        return builder.buildHeaders();
    }
}
